﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using TheVerge.Base.Models;
using Microsoft.Phone.Controls;

namespace TheVerge.Phone.Controls {
	/// <summary>
	/// Class was designed with the help from the following article:
	/// http://blogs.msdn.com/b/slmperf/archive/2011/06/30/windows-phone-mango-change-listbox-how-to-detect-compression-end-of-scroll-states.aspx
	/// </summary>
	public partial class InfiniteScroller : UserControl {

		#region Dependency Properties
		public DataTemplate ItemTemplate {
			get { return (DataTemplate)GetValue(ItemTemplateProperty); }
			set { SetValue(ItemTemplateProperty, value); }
		}

		public static readonly DependencyProperty ItemTemplateProperty =
				DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(InfiniteScroller), new PropertyMetadata(null));

		public object ItemsSource {
			get { return (object)GetValue(ItemsSourceProperty); }
			set { SetValue(ItemsSourceProperty, value); }
		}
		public static readonly DependencyProperty ItemsSourceProperty =
				DependencyProperty.Register("ItemsSource", typeof(object), typeof(InfiniteScroller), new PropertyMetadata(null));
		
		#endregion

		public InfiniteScroller() {
			InitializeComponent();
		}

		#region Event Handlers
        private void Listbox_AtTop(object sender, EventArgs e)
        {
            AtTheTop();
        }

        private void Listbox_ItemDrawn(object sender, ItemDrawnArgs args)
        {
            if (null == listbox.ItemsSource) return;

            var vm = DataContext as IVMEntries;

            if (null == vm) return;

            var idx = vm.IndexOf(args.DataItem);

            //-- If we've realized the last item, we should try and load more.
            if (idx > 0 && idx == vm.ItemsCount - 1)
                AtTheBottom();
        }

        private void AtTheTop() {
            var vm = DataContext as IVMEntries;
			if (vm != null)
				vm.Refresh();
		}

		private void AtTheBottom() {
			var vm = DataContext as IVMEntries;
			if (vm != null)
				vm.LoadMore();
		}
        #endregion
	}
}
